package com.chanzany.interview_secondary.jvm.jvm_03_fourReference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * 引用队列
 *  * Reference queues, to which registered reference objects are appended by the
 *  * garbage collector after the appropriate reachability changes are detected.
 *  对于已注册到引用队列的某个引用，其可达性变化被检测时，引用队列会赶在其被GC销毁前添加到其队列中
 */
public class ReferenceQueueDemo {
    public static void main(String[] args) {
        Object o = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        WeakReference<Object> weakReference = new WeakReference<>(o,referenceQueue);

        System.out.println(o);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll()); //null
        System.out.println("======================");
        o=null;
        System.gc();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace();}
        System.out.println(o);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());//java.lang.ref.WeakReference@4554617c
    }
}
